package flc.ast.fragment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hpplay.sdk.source.api.IConnectListener;
import com.hpplay.sdk.source.browse.api.IBrowseListener;
import com.hpplay.sdk.source.browse.api.LelinkServiceInfo;
import com.stark.cast.screen.CastScreenManager;

import java.util.List;

import flc.ast.AppConfig;
import flc.ast.R;
import flc.ast.activity.PlayLinkActivity;
import flc.ast.activity.SelAudioActivity;
import flc.ast.activity.SelPicActivity;
import flc.ast.activity.SelVideoActivity;
import flc.ast.activity.VideoFormatActivity;
import flc.ast.adapter.DeviceAdapter;
import flc.ast.databinding.FragmentPlayBinding;
import flc.ast.utils.Content;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link PlayFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class PlayFragment extends BaseNoModelFragment<FragmentPlayBinding> {

    private CastScreenManager mCastScreenManager;
    private boolean isSearch = false;
    private DeviceAdapter deviceAdapter;

    @Override
    protected int onCreate() {
        return R.layout.fragment_play;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mDataBinding.tvDisconnect.setOnClickListener(this);
        mDataBinding.tvRefresh.setOnClickListener(this);
        mDataBinding.llProVideo.setOnClickListener(this);
        mDataBinding.llProPicture.setOnClickListener(this);
        mDataBinding.llProAudio.setOnClickListener(this);
        mDataBinding.rlFormatConvert.setOnClickListener(this);
        mDataBinding.llLocalPlay.setOnClickListener(this);
        mDataBinding.llPlayLink.setOnClickListener(this);

        mDataBinding.rvDeviceList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        deviceAdapter = new DeviceAdapter();
        mDataBinding.rvDeviceList.setAdapter(deviceAdapter);
        deviceAdapter.addChildClickViewIds(R.id.tvDeviceItemSel);
        deviceAdapter.setOnItemChildClickListener(this);

        //注册投屏
        registerScreen();
    }

    @Override
    protected void onClickCallback(View v) {
        int id = v.getId();
        if (id == R.id.tvDisconnect) { //  断开连接
            Content.IsConnect = false;
            mCastScreenManager.disConnect();
            Content.ConnectName = "";
            mDataBinding.tvConnectStatus.setText(R.string.not_conn);
            mDataBinding.tvDeviceName.setVisibility(View.GONE);
            mDataBinding.tvDisconnect.setVisibility(View.INVISIBLE);
        } else if (id == R.id.tvRefresh) {  //刷新
            if (isSearch) return;
            isSearch = true;
            showDialog(getString(R.string.search_ing));
            mCastScreenManager.startBrowse();
        } else if (id == R.id.llProVideo) { //视频投屏
            if (!Content.IsConnect) {
                ToastUtils.showShort(R.string.please_conn_pro_device);
                return;
            }
            SelVideoActivity.type = 0;
            startActivity(SelVideoActivity.class);
        } else if (id == R.id.llProPicture) { //图片投屏
            if (!Content.IsConnect) {
                ToastUtils.showShort(R.string.please_conn_pro_device);
                return;
            }
            startActivity(SelPicActivity.class);
        } else if (id == R.id.llProAudio) { //音频投屏
            if (!Content.IsConnect) {
                ToastUtils.showShort(R.string.please_conn_pro_device);
                return;
            }
            startActivity(SelAudioActivity.class);
        } else if (id == R.id.rlFormatConvert) { //格式转换
            startActivity(VideoFormatActivity.class);
        } else if (id == R.id.llLocalPlay) { //本地播放
            SelVideoActivity.type = 1;
            startActivity(SelVideoActivity.class);
        } else if (id == R.id.llPlayLink) { //链接播放
            startActivity(PlayLinkActivity.class);
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        int id = view.getId();
        if (id == R.id.tvDeviceItemSel) {
            Content.IsConnect = true;
            mCastScreenManager.connect(deviceAdapter.getItem(position));
            Content.ConnectName = deviceAdapter.getItem(position).getName();
            mDataBinding.tvConnectStatus.setText(R.string.connected_text);
            mDataBinding.tvDeviceName.setText(Content.ConnectName);
            mDataBinding.tvDeviceName.setVisibility(View.VISIBLE);
            mDataBinding.tvDisconnect.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void initData() {

    }

    //注册投屏
    private void registerScreen() {
        CastScreenManager.init(AppConfig.TEST_APP_ID, AppConfig.TEST_APP_SECRET);
        mCastScreenManager = CastScreenManager.getInstance();
        mCastScreenManager.setListener(new CastScreenManager.AListener() {
            @Override
            public void onInit(boolean success) {
                dismissDialog();
                ToastUtils.showLong(success ? getString(R.string.init_suc) : getString(R.string.init_def));
                if (success) {
                    Content.IsInit = true;
                    isSearch = true;
                    showDialog(getString(R.string.search_ing));
                    mCastScreenManager.startBrowse();
                } else {
                    Content.IsInit = false;
                }
            }

            @Override
            public void onBrowse(int code, List<LelinkServiceInfo> list) {
                dismissDialog();
                isSearch = false;
                if (code == IBrowseListener.BROWSE_SUCCESS) {
                    if (deviceAdapter != null) {
                        mDataBinding.llDeviceNoData.setVisibility(View.GONE);
                        mDataBinding.rvDeviceList.setVisibility(View.VISIBLE);
                        deviceAdapter.setList(list);
                        //回显连接状态
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).getName().equals(Content.ConnectName)) {
                                list.get(i).setConnect(true);
                            }
                        }
                        deviceAdapter.notifyDataSetChanged();
                    } else {
                        mDataBinding.llDeviceNoData.setVisibility(View.VISIBLE);
                        mDataBinding.rvDeviceList.setVisibility(View.GONE);
                    }
                } else if (code == IBrowseListener.BROWSE_TIMEOUT) {
                    ToastUtils.showLong(R.string.search_over);
                } else if (code == IBrowseListener.BROWSE_ERROR_AUTH || code == IBrowseListener.BROWSE_ERROR_AUTH_TIME) {
                    ToastUtils.showLong(R.string.auth_def);
                }
            }

            @Override
            public void onConnect(LelinkServiceInfo lelinkServiceInfo, int connectType) {
                String strProtocol = getString(R.string.no_agreement);
                switch (connectType) {
                    case IConnectListener.TYPE_LELINK:
                        strProtocol = getString(R.string.lelian_agreement);
                        break;
                    case IConnectListener.TYPE_DLNA:
                        strProtocol = getString(R.string.dlna_agreement);
                        break;
                    case IConnectListener.TYPE_IM:
                        strProtocol = getString(R.string.im_agreement);
                        break;
                }
                if (lelinkServiceInfo.getName() != null && !TextUtils.isEmpty(lelinkServiceInfo.getName())) {
                    Content.IsConnect = true;
                    Content.ConnectName = lelinkServiceInfo.getName();
                } else {
                    Content.IsConnect = false;
                    Content.ConnectName = "";
                }
                ToastUtils.showLong(getString(R.string.conn_device) + lelinkServiceInfo.getName() + getString(R.string.agreement_to) + strProtocol);
            }

            @Override
            public void onDisconnect(LelinkServiceInfo lelinkServiceInfo, int what, int extra) {
                Content.IsConnect = false;
                String text = getString(R.string.break_device) + lelinkServiceInfo.getName();
                if (what == IConnectListener.WHAT_HARASS_WAITING) {// 防骚扰，等待用户确认
                    // 乐播投屏防骚扰等待消息
                    text = lelinkServiceInfo.getName() + getString(R.string.wait_right);
                } else if (what == IConnectListener.WHAT_DISCONNECT) {
                    switch (extra) {
                        case IConnectListener.EXTRA_HARASS_REJECT:// 防骚扰，用户拒绝投屏
                            text = lelinkServiceInfo.getName() + getString(R.string.conn_refuse);
                            break;
                        case IConnectListener.EXTRA_HARASS_TIMEOUT:// 防骚扰，用户响应超时
                            text = lelinkServiceInfo.getName() + getString(R.string.saorao_request_over);
                            break;
                        case IConnectListener.EXTRA_HARASS_BLACKLIST:// 防骚扰，该用户被加入黑名单
                            text = lelinkServiceInfo.getName() + getString(R.string.black_list);
                            break;
                        default:
                            text = lelinkServiceInfo.getName() + getString(R.string.conn_break);
                            break;
                    }
                } else if (what == IConnectListener.WHAT_CONNECT_FAILED) {
                    switch (extra) {
                        case IConnectListener.EXTRA_CONNECT_DEVICE_OFFLINE:
                            text = lelinkServiceInfo.getName() + getString(R.string.no_online);
                            break;
                        default:
                            text = lelinkServiceInfo.getName() + getString(R.string.conn_def);
                            break;
                    }
                }
                ToastUtils.showLong(text);
            }
        });
        if (!Content.IsInit) {
            showDialog(getString(R.string.init_ing));
            mCastScreenManager.init();
        }
    }


}